//
//  ArticleViewController.swift
//  SCUTWiki
//
//  Created by Wu Weisong on 2020/12/15.
//  Copyright © 2020 wwszhw. All rights reserved.
//

import UIKit
import AudioToolbox

protocol StarDelegate {
    func changeCollection(collected: Bool)
}

class ArticleViewController: UIViewController {

    var starDelegate:StarDelegate?
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var contentTextView: UITextView!
    @IBOutlet weak var starButton: UIBarButtonItem!
    
    var articleObject:ArticleModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let article = self.articleObject{
            titleLabel.text = article.title
            contentTextView.text = article.content
            if article.collected {
                starButton.setBackgroundImage(UIImage(named: "Star"), for: .normal, barMetrics: .default)
            }else{
                starButton.setBackgroundImage(UIImage(named: "StarOff"), for: .normal, barMetrics: .default)
            }
        }
    }
    
    @objc func backClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func tapOnStarButton(_ sender: Any) {
        if articleObject!.collected {//如果点击按钮时是收藏状态
            articleObject?.collected = false
            starButton.setBackgroundImage(UIImage(named: "StarOff"), for: .normal, barMetrics: .default)
        }else{//如果点击按钮时是未收藏状态
            articleObject?.collected = true
            starButton.setBackgroundImage(UIImage(named: "Star"), for: .normal, barMetrics: .default)
            // 播放声音
            AudioServicesPlayAlertSound(1000)
        }
        starDelegate?.changeCollection(collected: articleObject!.collected)//更改tableview和数据库中的数据
    }
}
